<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="connection-form">
    <el-form-item label="数据库类型" prop="dbType">
      <el-select v-model="form.dbType" placeholder="请选择数据库类型">
        <el-option label="MySQL" value="mysql" />
        <el-option label="PostgreSQL" value="postgresql" />
      </el-select>
    </el-form-item>

    <el-form-item label="主机地址" prop="host">
      <el-input v-model="form.host" placeholder="localhost" />
    </el-form-item>

    <el-form-item label="端口" prop="port">
      <el-input-number v-model="form.port" :min="1" :max="65535" />
    </el-form-item>

    <el-form-item label="数据库名" prop="database">
      <el-input v-model="form.database" placeholder="请输入数据库名称" />
    </el-form-item>

    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" placeholder="请输入用户名" />
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" :loading="loading" @click="handleSubmit"> 生成文档 </el-button>
      <el-button @click="handleReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { DatasourceConnection } from '@/types/document'

interface Emits {
  (e: 'submit', data: DatasourceConnection): void
}

const emit = defineEmits<Emits>()
const props = defineProps<{
  loading?: boolean
}>()

const formRef = ref<FormInstance>()
const form = reactive<DatasourceConnection>({
  dbType: 'mysql',
  host: 'localhost',
  port: 3306,
  database: 'im_db',
  username: 'root',
  password: 'SV^u8@rB8Zw9',
})

const rules: FormRules = {
  dbType: [{ required: true, message: '请选择数据库类型', trigger: 'change' }],
  host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口号', trigger: 'blur' }],
  database: [{ required: true, message: '请输入数据库名', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    emit('submit', { ...form })
  } catch (error) {
    // 验证失败
  }
}

const handleReset = () => {
  formRef.value?.resetFields()
  form.port = 3306
  form.dbType = 'mysql'
}
</script>

<style scoped>
.connection-form {
  max-width: 500px;
}
</style>
